import { Image, InfiniteScroll, List } from 'antd-mobile';
import { useEffect, useState } from 'react';
import { ListRes, fetchListAPI } from '@/apis/list';
import { useNavigate } from 'react-router-dom';

type Props = {
   channel_id:string
}

const HomeList = (props:Props) => {
   const {channel_id} = props
   const navigate = useNavigate()
   const [listRes,setListRes] = useState<ListRes>({
      results:[],
      pre_timestamp:'' + new Date().getTime()
   })
   useEffect(()=>{
      fetchListAPI({
         channel_id,
         timestamp: '' + new Date().getTime()
      }).then(res=>{
         setListRes({
            results:res.data.data.results,
            pre_timestamp:res.data.data.pre_timestamp
         })
      }).catch((err)=>{
         throw new Error(err)
      })
   },[channel_id])
   const [hasMore,setHasMore] = useState(true)
   const loadMore = async () => {
      // 加载数据
      fetchListAPI({
         channel_id,
         timestamp: listRes.pre_timestamp
      }).then(res=>{
         // 拼接新数据 + 存取下一次请求的时间戳
         setListRes({
            results:[...listRes.results,...res.data.data.results],
            pre_timestamp:res.data.data.pre_timestamp
         })
         if(res.data.data.results.length === 0){
            setHasMore(false)
         }
      }).catch((err)=>{
         throw new Error(err)
      })
   }
   // 跳转到详情
   const goToDetail = (id:string) => {
      navigate(`/detail?id=${id}`)
   }
   return (
      <>
         <List>
            {listRes.results.map((item) => (
               <List.Item
                  onClick={()=>goToDetail(item.art_id)}
                  key={item.art_id}
                  prefix={
                     <Image
                        src={item.cover.images?.[0]}
                        style={{ borderRadius: 20 }}
                        fit="cover"
                        width={40}
                        height={40}
                     />
                  }
                  description={item.pubdate}
               >
                  {item.title}
               </List.Item>
            ))}
         </List>
         <InfiniteScroll threshold={10} loadMore={loadMore} hasMore={hasMore}></InfiniteScroll>
      </>
   )
}

export default HomeList